<?php
error_reporting (E_ALL ^ E_NOTICE);
header('Refresh: 10');
require("../includes/config.inc.php"); 
require("../includes/Database.class.php"); 
require("../includes/GPSFunction.php"); 
require("../includes/smsSF.php"); 
require("../includes/mailSMTP.php"); 

$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 
function gpspathAll($path1)
{
	$file1 = @fopen($path1, "r");
	if($file1)
	{
		while(!@feof($file1))
		{
			$data= @fgets($file1);				 
		}
		$data = getSortedData($data);
		return $data;
	}
	else
	{
		return 0;
	
	}
	@fclose($file1);
}

function ReverseSordData($data1)
{
	$dataArr = explode('#',$data1);
	for($i=0;$i<count($dataArr)-1;$i++)
	{
		$dtArray = explode(',',$dataArr[$i]);
		//print_r($dtArray);
		$newDate=$dtArray[9];
		$newdtArray1[$newDate] = $dataArr[$i];
	}
	ksort($newdtArray1);
 	$data = end($newdtArray1)."#";
	return $data;
} 
function getMyTimeDiff($t1,$t2)
{
	$a1 = explode(":",$t1);
	$a2 = explode(":",$t2);
	$time1 = (($a1[0]*60*60)+($a1[1]*60)+($a1[2]));
	$time2 = (($a2[0]*60*60)+($a2[1]*60)+($a2[2]));
	$diff = abs($time1-$time2);
	
	return $diff;
}
function getClosestElement($array, $value)
{
$size = count($array);
if ($size > 0) {

	$diff = abs(max($array) - $value);
	$ret = max($array);
 while (list($key, $va) = each($array)) {
		 if(isset($va)){$temp = abs($va - $value);}

			if ($temp < $diff) {
			 $diff = $temp;
			 $ret = $va;
			 $k = $key;
			}
		}
			 return $k;
} else {
	  return NULL;
 }

}


if(isset($_GET[gpsdata]) && $_GET[gpsdata])
{
	$gpsdata = str_replace("$","",$_GET[gpsdata]);
	$gpsdata = str_replace("@","",$gpsdata);
	$gpsdata = explode(",",$gpsdata);
	//$gpsdata[8] = date("d-m-Y");
	if($gpsdata[8] == date("d-m-Y"))
	{
		$getDevice = "select * from tb_deviceinfo,tb_client_subscription where tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_imeiId = '".$gpsdata[0]."'";
		$resDevice = $db->query($getDevice);
		$date_offline = date('d-m-Y');
		if($db->affected_rows > 0)
		{	
			$fetDevice = $db->fetch_array($resDevice);
			$renewDate = date("d-m-Y",strtotime("-1 days ".($fetDevice[tcs_noOfMonths]) ."months ".$fetDevice[tcs_renewalDateFrom]));
			if(strtotime($date_offline) <= strtotime($renewDate))
			{
				$path1=DATAPATH.date('d-m-Y',strtotime($gpsdata[8]))."/".$gpsdata[0].".txt";
				$mydata=gpspathAll($path1);
				$data1=explode("#",$mydata);
				$data2=explode("@",$data1[count($data1)-2]);
				if(count($data2)>1)
				{
					$data3=explode(",",$data2[1]);			
					//print_r($data3);
					$lat=calLat($data3[2]);
					$lng=calLong($data3[1]);
					
					$devDateTime = $data3[8]." ".$data3[9];
					$curTime1 = explode(":",date("H:i",strtotime($data3[9])));
					$curTime = ($curTime1[0] * 60) + $curTime1[1];			
					
					$devImei = $data3[0];						
					$sessionid = $_GET["sessionid"] ;
				}
					
					
				$liveData = $data1[count($data1)-2];
				//$liveData1=explode("#",$liveData);
				$liveData2=explode("@",$liveData);
				if(count($liveData2)>1)
				{
					$liveData3 = explode(",",$liveData2[1]);
					
					$getLiveData = "SELECT * FROM tb_livegps_info WHERE tli_imei = '".$gpsdata[0]."'";
					$exeLiveData = $db->query($getLiveData);
					if($db->affected_rows > 0)
					{
						$fetLiveData = $db->fetch_array($exeLiveData);
						
						if(strtotime(date("d-m-Y",strtotime($fetLiveData[tli_date]))) < strtotime(date("d-m-Y",strtotime($gpsdata[8]))))
						{
							$kmdata['tmsi_clientId'] = $fetDevice[di_clientId];
							$kmdata['tmsi_imei'] = $gpsdata[0];
							$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($fetLiveData[tli_date]));
							$kmdata['tmsi_kmpd'] = $fetLiveData[tli_distance];
							
							//print_r($kmdata);
							//exit;
							$db->query_insert("tb_speed_meter_info", $kmdata);
							
							
							$lastData1=explode("#",$fetLiveData[tli_parameter]);
							$lastData2=explode("@",$lastData1[count($lastData1)-2]);
							if(count($lastData2)>1)
							{
								$lastData3=explode(",",$lastData2[1]);
								
								$lastDist = getDistance(calLat($lastData3[2]), calLong($lastData3[1]), calLat($liveData3[2]), calLong($liveData3[1]));
								
								//echo "elt ".calLat($lastData3[2]).", eln ".calLong($lastData3[1]).", nlt ".calLat($liveData3[2]).", nln ".calLong($liveData3[1])." ".$fetLiveData[tli_distance]." ".$lastDist;
								$livedata["tli_imei"] = $gpsdata[0];
								$livedata["tli_parameter"] = $liveData."#";
								$livedata["tli_distance"] = $fetLiveData[tli_distance] + round($lastDist,4);
								$livedata["tli_date"] = $liveData3[8];
								$livedata["tli_time"] = $liveData3[9];
								$livedata["tli_updateTime"] = 'NOW()';
								//print_r($livedata);
								//exit;
								$db->query_update("tb_livegps_info", $livedata, "tli_imei = ".$gpsdata[0]);
							}
							
						}
						else if(strtotime(date("d-m-Y",strtotime($fetLiveData[tli_date]))) == strtotime(date("d-m-Y",strtotime($gpsdata[8]))))
						{
							$lastData1=explode("#",$fetLiveData[tli_parameter]);
							$lastData2=explode("@",$lastData1[count($lastData1)-2]);
							if(count($lastData2)>1)
							{
								$lastData3=explode(",",$lastData2[1]);
								
								$lastDist = getDistance(calLat($lastData3[2]), calLong($lastData3[1]), calLat($liveData3[2]), calLong($liveData3[1]));
								
								//echo "elt ".calLat($lastData3[2]).", eln ".calLong($lastData3[1]).", nlt ".calLat($liveData3[2]).", nln ".calLong($liveData3[1])." ".$fetLiveData[tli_distance]." ".$lastDist;
								$livedata["tli_imei"] = $gpsdata[0];
								$livedata["tli_parameter"] = $liveData."#";
								$livedata["tli_distance"] = $fetLiveData[tli_distance] + round($lastDist,4);
								$livedata["tli_date"] = $liveData3[8];
								$livedata["tli_time"] = $liveData3[9];
								$livedata["tli_updateTime"] = 'NOW()';
								//print_r($livedata);
								//exit;
								$db->query_update("tb_livegps_info", $livedata, "tli_imei = ".$gpsdata[0]);
							}
						}
						
					}
					else
					{
						$livedata["tli_imei"] = $gpsdata[0];
						$livedata["tli_parameter"] = $liveData."#";
						$livedata["tli_distance"] = 0;
						$livedata["tli_date"] = $liveData3[8];
						$livedata["tli_time"] = $liveData3[9];
						$livedata["tli_updateTime"] = 'NOW()';
						//print_r($livedata);
						//exit;
						$db->query_insert("tb_livegps_info", $livedata);
					}
				}
				
				//1. Geofence alert check and process				
				
				$getGeofenceInfo = "SELECT * FROM tb_assigngeofence WHERE tag_diId = ".$fetDevice[di_id]." AND tag_isActive = 1 ORDER BY tag_id ASC";
				$resGeofenceInfo = $db->query($getGeofenceInfo);
				if($db->affected_rows > 0)
				{
					
					//exit;
					while($fetGeofence = $db->fetch_array($resGeofenceInfo))
					{
						$donotTime = explode("#",$fetGeofence[tag_donotTime]);
						//print_r($donotTime);
						$sTime1 = explode(":",date("H:i",strtotime($donotTime[0])));
						$eTime1 = explode(":",date("H:i",strtotime($donotTime[1])));
						
						$sTime = ($sTime1[0] * 60) + $sTime1[1];
						$eTime = ($eTime1[0] * 60) + $eTime1[1];
						$dffTime = intval($eTime) - intval($sTime);
						
						//echo $dffTime." = ".$eTime." ".$sTime;
						
						$spltTime = explode(" ",$donotTime[1]);
						
						if($dffTime < 0 && $spltTime[1] == "AM")
						{
							//$eTime = ( ($eTime1[0]+24) * 60) + $eTime1[1];
							$sTime = ($eTime1[0] * 60) + $eTime1[1];
							$eTime = ($sTime1[0] * 60) + $sTime1[1];
							
						}
						else
						{


							$sTime = ($sTime1[0] * 60) + $sTime1[1];
							$eTime = ($eTime1[0] * 60) + $eTime1[1];
						}

						//echo "<br>".$fetGeofence[tag_inout]." aa ".$sTime." > ".$curTime." < ".$eTime;
						if(($sTime >= $curTime && $eTime >= $curTime) || ($curTime >= $sTime && $curTime >= $eTime))
						{
							
							//echo $fetGeofence[tag_inout]." aa ".$curTime." ss ".$sTime." ".$eTime;
							
							$gpspts = $fetGeofence[tag_geofenceId]."#".$fetGeofence[tag_id]."#".$fetGeofence[tag_alertSrc]."#".$fetGeofence[tag_noofTimes]."#".$fetGeofence[tag_inout];
							$resSrv1= explode("#",$gpspts);	
							
							//print_r($resSrv1);
							$getDevice = "SELECT * FROM tb_geofence_info WHERE tgi_id = ".$fetGeofence[tag_geofenceId]." AND tgi_isActive = 1";
							$resDevice = $db->query($getDevice);
							if($db->affected_rows > 0)
							{
								$fetDevice = $db->fetch_array($resDevice);
								$lat_lng = explode(",",$fetDevice[tgi_latLong]);		
								$radius = $fetDevice[tgi_radius];
								
								if($fetDevice[tgi_geoType] == "CIRCLE")
								{
									$latlngArr = drawCircle($lat_lng[0],$lat_lng[1],$radius);
									//print_r($latlngArr);
									$res = getGeofenceStatus($latlngArr,$lat,$lng);
								}
								elseif($fetDevice[tgi_geoType] == "POLYGON")
								{
									$ltln1 = explode("#",$fetDevice[tgi_polyCoordinates]);
									for($k = 0 ;$k < count($ltln1)-1; $k++)
									{								
										$latlngPolyArr[] = $ltln1[$k];										
									}
									//print_r($latlngPolyArr);
									//echo " , ".$lat." , ".$lng."<br>";
									$res = getGeofenceStatus($latlngPolyArr,$lat,$lng);
								}
								//echo "<br>";
								
								//exit;
								if($fetGeofence[tag_inout] == "both")
								{
									if($res)
									{
										smsBothAlertFunc($resSrv1[0],$resSrv1[1],$resSrv1[2],$resSrv1[3],$resSrv1[4],$devDateTime,$devImei,"in");
									}
									else
									{
										smsBothAlertFunc($resSrv1[0],$resSrv1[1],$resSrv1[2],$resSrv1[3],$resSrv1[4],$devDateTime,$devImei,"out");
									}
								}
								else
								{
			
									if($res)
									{
										smsmAlertFunc($resSrv1[0],$resSrv1[1],$resSrv1[2],$resSrv1[3],$resSrv1[4],$devDateTime,$devImei,"in");
									}
									else
									{
										smsmAlertFunc($resSrv1[0],$resSrv1[1],$resSrv1[2],$resSrv1[3],$resSrv1[4],$devDateTime,$devImei,"out");
									}
								}
							}
						}
					}					
				}
				
				
				//2. Other alert check and process
				
				$sql = "select * from tb_device_alert_info,tb_clientinfo,tb_deviceinfo,tb_device_model WHERE model = di_deviceModel AND di_id = tdai_deviceId AND ci_id = tdai_clientId AND tdai_active = 1 AND di_imeiId = '".$gpsdata[0]."' AND tdai_status = 0 order by tdai_id ASC";
				$rows = $db->query($sql);
				if($db->affected_rows > 0)
				{
					while($record = $db->fetch_array($rows))
					{
						if($record[di_deviceName])
							$devName = $record[di_deviceName];
						else
							$devName = $record[di_deviceId];
						
						if($record[tag_inout] == "in")
							$status = "entered zone";
						else if($record[tag_inout] == "out")
							$status = "left zone";		
						else if($record[tag_inout] == "both")
						{
							if($inoutStatus == "in")
								$status = "entered zone";
							else if($inoutStatus == "out")
								$status = "left zone";
					
						}
						
						$getReseller = "select * from tb_clientinfo where ci_id = ".$record[ci_clientId];
						$resReseller = mysql_query($getReseller);
						$fetReseller = @mysql_fetch_assoc($resReseller);	
						
						if($record[tdai_alertBy] == "Date" && $record[tdai_alertSrc] == date("d-m-Y"))		// if Date alert
						{							
							$mailMsg ='You have created Date Alert for Your Vehicle ' . strip_tags($devName) . ' to '.date("d,M Y",strtotime($record[tdai_alertSrc])).' for the ';
							$mailMsg .= 'Purpose of ' . strip_tags(ucfirst($record[tdai_purpose])).'.';
							$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));

							//OLD SMS Format					
							/*	
							$smsMsg = "Date Alert: ".$devName;
							$smsMsg .= " ".ucfirst($record[tdai_description]);
							$smsMsg .= " by ".$fetReseller[ci_weburl];
							*/
	
	$smsMsg ='This message is to remind you about '.strip_tags(ucfirst($record[tdai_purpose])).' of vehicle '.$devName.' by '.$fetReseller[ci_weburl];
	
							if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "Date"))
							{
								$data['tdai_status'] = 1;
								$data['tdai_deliveryTime'] = date("Y-m-d H:i:s");
								if($db->query_update("tb_device_alert_info", $data , "tdai_id=".$record[tdai_id]))
									echo "done";
								else echo "no";
							}
						}
						else if($record[tdai_alertBy] == "Meter")	// if Meter alert
						{
							$sdate = date("d-m-Y",strtotime($record[di_createDate]));
							$edate = date("d-m-Y");
							
							$z = GetDays($sdate, $edate);
							for($y=0; $y<count($z); $y++)
							{
								$getDateReading = "SELECT * FROM tb_speed_meter_info WHERE tmsi_clientId = ".$record[di_clientId]." AND tmsi_imei = '".$record[di_imeiId]."' AND tmsi_readDate = '".date('Y-m-d',strtotime($z[$y]))."'";
								$resDateReading = $db->query($getDateReading);
					
								if($db->affected_rows == 0)
								{
									$path=DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$record[di_imeiId].".txt";
									$km = funKMPerDayofDevice($path);
									$kmdata['tmsi_clientId'] = $record[di_clientId];
									$kmdata['tmsi_imei'] = $record[di_imeiId];
									$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($z[$y]));
									$kmdata['tmsi_kmpd'] = $km[0];
									$db->query_insert("tb_speed_meter_info", $kmdata);
								}
								else
								{
									$sToTime = strtotime($z[$y]);
									$eToTime = strtotime(date("d-m-Y"));
									if($sToTime == $eToTime )
									{
										$fetDateReading = $db->fetch_array($resDateReading);

										$path=DATAPATH.date('d-m-Y',strtotime($z[$y]))."/".$record[di_imeiId].".txt";
										$km = explode(",",funKMPerDayofDevice($path));
										//print_r($km);
										$kmdata['tmsi_clientId'] = $record[di_clientId];
										$kmdata['tmsi_imei'] = $record[di_imeiId];
										$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($z[$y]));
										$kmdata['tmsi_kmpd'] = $km[0];
										
										$db->query_update("tb_speed_meter_info", $kmdata, "tsmi_id = ".$fetDateReading[tsmi_id]);
									}
								}
								
								//echo "<br><br>";
							}
							//print_r($record);
							
							$getReading = "SELECT SUM(tmsi_kmpd) as dist FROM tb_speed_meter_info WHERE tmsi_clientId = ".$record[di_clientId]." AND tmsi_imei = '".$record[di_imeiId]."' group by tmsi_imei";
							$resReading = $db->query($getReading);
							if($db->affected_rows > 0 )
							{
							
								$fetReading = mysql_fetch_assoc($resReading);
								$odoMeter = $record[di_odoMeter] + $fetReading[dist];
							}
							else
							{
								$odoMeter = $record[di_odoMeter];
							}
							//echo $record[tdai_alertSrc]." - ".$odoMeter;
							
							if($record[tdai_alertSrc] == $odoMeter || (($record[tdai_alertSrc] - $odoMeter) > 2 && ($record[tdai_alertSrc] - $odoMeter) <= -2))
							{
								$mailMsg ='You have created Odometer Alert for Your Vehicle ' . strip_tags($devName) . ' on '.date("d,M Y",strtotime($record[tdai_createDate])).' for the ';
								$mailMsg .= 'Purpose of ' . strip_tags(ucfirst($record[tdai_purpose])).'.';
								$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description])); 
								
								//OLD SMS Format
								/*
								$smsMsg = "Odometer Alert: ".$devName;
								$smsMsg .= " ".ucfirst($record[tdai_description]);
								$smsMsg .= " by ".$fetReseller[ci_weburl];
								*/
								
								//NEW SMS Format
								
								$smsMsg = 'Odometer Alert: Your odometer reading is '.$odoMeter.' now. by '.$fetReseller[ci_weburl];
								
								
								if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "Odometer"))
								{
									$data['tdai_status'] = 1;
									$data['tdai_deliveryTime'] = date("Y-m-d H:i:s");
									if($db->query_update("tb_device_alert_info", $data , "tdai_id=".$record[tdai_id]))
										echo "done";
									else echo "no";
								}
							}
							
						}
						else if($record[tdai_alertBy] == "OverSpeed")	// if Overspeed alert
						{
							$data1=explode("#",$mydata);
							$data2=explode("@",$data1[count($data1)-2]);		
							if(count($data2)>1)
							{
								$data3=explode(",",$data2[1]);			
								$devDateTime = $data3[8]." ".$data3[9];
								$spdLtd = explode("#",$record[tdai_alertSrc]);
							}	
							$getAlertImeiInfo = "SELECT * FROM tb_overspeed_alert_info WHERE toai_dai_id = ".$record[tdai_id]." and toai_createDate like '".date("Y-m-d")."%' ORDER BY toai_id DESC LIMIT 0,1";
							$resAlertImeiInfo = $db->query($getAlertImeiInfo);
							if($db->affected_rows == 0)		// first time vehicle reached max speed
							{								
								if($data3[3] >= $spdLtd[1])
								{
									$mailMsg ='Your vehicle ' . strip_tags($devName) . ' has exceeded the normal speed by '.$data3[3].' kmph. So kindly please check the vehicle.';
									$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
									
									//OLD SMS Format
									/*
									$smsMsg = "Dear Client, Your Vehicle ".$devName;
									$smsMsg .= " has exceeded the normal speed by ".$data3[3]." kmph. So kindly please check the vehicle.";
									$smsMsg .= " by ".$fetReseller[ci_weburl];
									*/
									
									//NEW SMS Format
									$smsMsg = 'Dear Client, your vehicle '.$devName.' has crossed normal speed limit. Now it is running at '.$data3[3].' Kmph. Please check. by '.$fetReseller[ci_weburl];
										
									if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "OverSpeed"))
									{
										$data['toai_dai_id'] = $record[tdai_id];
										$data['toai_maxSpeed'] = $spdLtd[1];
										$data['toai_devMaxSpeed'] = $data3[3];
										$data['toai_status'] = 0;
										$data['toai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_insert("tb_overspeed_alert_info", $data))
											echo "done";
										else echo "no";
									}
								}
							}
							else
							{
								$fetAlertImeiInfo = $db->fetch_array($resAlertImeiInfo);
								//print_r($fetAlertImeiInfo);
								
								// when vehicle reached low speed no alert & when vehicle reached max speed send alert
								if($fetAlertImeiInfo[toai_minSpeed] == 0 && $fetAlertImeiInfo[toai_maxSpeed] != 0 && $data3[3] <= $spdLtd[0])	
								{
									$data['toai_minSpeed'] = $spdLtd[0];
									$data['toai_devMinSpeed'] = $data3[3];
									$data['toai_status'] = 1;
									$data['toai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
									//print_r($data);
									//exit;
									if($db->query_update("tb_overspeed_alert_info", $data , "toai_id=".$fetAlertImeiInfo[toai_id]))
										$res = 1;
									else $res = 0;
								}
								else if($fetAlertImeiInfo[toai_minSpeed] != 0 && $fetAlertImeiInfo[toai_maxSpeed] != 0 && $data3[3] >= $spdLtd[1])
								{
									$mailMsg ='Your vehicle ' . strip_tags($devName) . ' has exceeded the normal speed by '.$data3[3].' kmph. So kindly please check the vehicle.';
									$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
									
									//OLD SMS Format
									/*
									$smsMsg = "Dear Client, Your Vehicle ".$devName;
									$smsMsg .= " has exceeded the normal speed by ".$data3[3]." kmph. So kindly please check the vehicle.";
									$smsMsg .= " by ".$fetReseller[ci_weburl];
									*/
									
									//NEW SMS Format
									$smsMsg = 'Dear Client, your vehicle '.$devName.' has crossed normal speed limit. Now it is running at '.$data3[3].' Kmph. Please check. by '.$fetReseller[ci_weburl];
									
									if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "OverSpeed"))
									{
										$data['toai_dai_id'] = $record[tdai_id];
										$data['toai_maxSpeed'] = $spdLtd[1];
										$data['toai_devMaxSpeed'] = $data3[3];
										$data['toai_status'] = 0;
										$data['toai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_insert("tb_overspeed_alert_info", $data))
											echo "done";
										else echo "no";
									}	
								}
							}
							
						}
						elseif($record[tdai_alertBy] == "OverStay")	//// if Overstay alert
						{
							$donotTime = explode("#",$record[tdai_donotTime]);
							//print_r($donotTime);
							$sTime1 = explode(":",date("H:i",strtotime($donotTime[0])));
							$eTime1 = explode(":",date("H:i",strtotime($donotTime[1])));
							
							$sTime = ($sTime1[0] * 60) + $sTime1[1];
							$eTime = ($eTime1[0] * 60) + $eTime1[1];
							$dffTime = intval($eTime) - intval($sTime);
							
							//echo $dffTime." = ".$eTime." ".$sTime;
							
							$spltTime = explode(" ",$donotTime[1]);
							
							if($dffTime < 0 && $spltTime[1] == "AM")
							{
								//$eTime = ( ($eTime1[0]+24) * 60) + $eTime1[1];
								$sTime = (($eTime1[0]+12) * 60) + $eTime1[1];
								$eTime = ($sTime1[0] * 60) + $sTime1[1];
								
							}
							else
							{
								$sTime = ($sTime1[0] * 60) + $sTime1[1];
								$eTime = ($eTime1[0] * 60) + $eTime1[1];
							}
	
								//echo "<br>".$fetGeofence[tag_inout]." aa ".$sTime." > ".$curTime." < ".$eTime;
								if(($sTime >= $curTime && $eTime >= $curTime) || ($curTime >= $sTime && $curTime >= $eTime))
								{
								
								$data1=explode("#",$mydata);
								$strStayTime = "";
								
								$getAlertImeiInfo = "SELECT * FROM tb_overstay_info WHERE tosi_dai_id = ".$record[tdai_id]." and tosi_createDate like '".date("Y-m-d")."%' ORDER BY tosi_id DESC LIMIT 0,1";
								$resAlertImeiInfo = $db->query($getAlertImeiInfo);
								$affRow = $db->affected_rows;
								
								for($j1 = count($data1); $j1 > 0; $j1--)		
								{
									$data2=explode("@",$data1[$j1]);
									if(count($data2)>1)
									{
										$data3=explode(",",$data2[1]);	
										$mph = round($data3[3]);
										$devDateTime = $data3[8]." ".$data3[9];
										
										if($data3[3] == 0 && $strStayTime =='' && $j1 == (count($data1) - 2 ))
										{
											$sstime1 = explode(":",date("H:i",strtotime($data3[9])));
											$strStayTime = (($sstime1[0] * 60) + $sstime1[1]);													
										}
										else if($data3[3] == 0 && $strStayTime !='' && $affRow == 0)
										{	
											$eetime1 = explode(":",date("H:i",strtotime($data3[9])));
											$endStayTime = (($eetime1[0] * 60) + $eetime1[1]);	
	
											
											$diffTime = round($strStayTime - $endStayTime);
											
											if($diffTime == $record[tdai_alertSrc])
											{
												echo 'First '.$data3[9]." ".$strStayTime.' '.$record[tdai_alertSrc]."<br>";
												$mailMsg ='Your vehicle ' . strip_tags($devName) . ' has exceeded the over stay time limit '.$record[tdai_alertSrc].' mins. So kindly please check the vehicle.';
												$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
												
												//OLD SMS Format
												/*
												$smsMsg = "Dear Client, Your Vehicle ".$devName;
												$smsMsg .= " has exceeded the over stay time limit ".$record[tdai_alertSrc]." mins. So kindly please check the vehicle.";
												$smsMsg .= " by ".$fetReseller[ci_weburl];
												*/
												
												//NEW SMS Format
											$smsMsg = 'Dear Client, your vehicle '.$devName.' has crossed stay limit '.$record[tdai_alertSrc].' minutes. Please check. by '.$fetReseller[ci_weburl];
												
												if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "OverStay"))
												{
													$data['tosi_dai_id'] = $record[tdai_id];
													$data['tosi_startTime'] = $endStayTime;
													$data['tosi_stopTime'] = $strStayTime;
													$data['tosi_diff'] = $diffTime;
													$data['tosi_status'] = 1;
													$data['tosi_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
													print_r($data);
													/*exit;*/
													if($db->query_insert("tb_overstay_info", $data))
														echo "Done";
													else echo "no";												
												}
												
												break;
											}					
											//$strStayTime = "";
										}	
										else if($data3[3] > 0 && $affRow > 0  && $j1 == (count($data1) - 2 ))
										{
											
											$fetAlertImeiInfo = $db->fetch_array($resAlertImeiInfo);
											print_r($fetAlertImeiInfo);
											//echo $data3[3]."<br>";
											//echo '<br>'.$data3[9]." - ".$strStayTime.' '.$record[tdai_alertSrc]."<br>";
											
											
											
											$wtime1 = explode(":",date("H:i",strtotime($data3[9])));
											$whrStayTime = (($wtime1[0] * 60) + $wtime1[1]);
											
											$lasttime1 = explode(":",date("H:i",strtotime($fetAlertImeiInfo[tosi_deliveryTime])));
											$lastStayTime = (($lasttime1[0] * 60) + $lasttime1[1]);
											
											echo $diffTime = round($whrStayTime - $lastStayTime);
											
											echo '<br>'.$data3[9]." - ".$fetAlertImeiInfo[tosi_deliveryTime]."<br>"." ".$diffTime." = ".$whrStayTime.' - '.$lastStayTime;
											//$strStayTime ='';
											$delStayTime = "DELETE FROM tb_overstay_info WHERE tosi_id = ".$fetAlertImeiInfo[tosi_id];
											//$resStayTime = $db->query($delStayTime);
											
											break;
										}			
									}
								}
								
							}
						
						}
						elseif($record[tdai_alertBy] == "LowBattery")	//// if LowBattery alert
						{
							$data1=explode("#",$mydata);
							$data2=explode("@",$data1[count($data1)-2]);
							$devDateTime = $data3[8]." ".$data3[9];
							if(count($data2)>1)
							{
								$data3=explode(",",$data2[1]);			
								$d =preg_split("/[\s,]+/",$data3[7]);				
								  foreach($d as $e){					
									  if(substr($e,0,3)=='[67'){
										$lowbatsval  = str_replace(array('[67=',']'),'',$e); 
										break;
									  }					  
								  }				
							}
							
							if(strlen($lowbatsval) > 3)
							{
							 $lowbatsval = round($lowbatsval/100);
							 $getAlertImeiInfo = "SELECT * FROM tb_lowbattery_alert_info WHERE tlai_dai_id = ".$record[tdai_id]." and tlai_createDate like '".date("Y-m-d")."%' ORDER BY tlai_id DESC LIMIT 0,1";
							$resAlertImeiInfo = $db->query($getAlertImeiInfo);
								if($db->affected_rows == 0)
								{	
									if( $lowbatsval <= $record[tdai_alertSrc])
									{	
										$mailMsg ='Your vehicle ' . strip_tags($devName) . ' battery is low. So kindly please check the vehicle.';
										$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
										
										//OLD SMS Format
										/*
										$smsMsg = "Dear Client, Your Vehicle ".$devName;
										$smsMsg .= " battery is low. So kindly please check the vehicle.";
										$smsMsg .= " by ".$fetReseller[ci_weburl];
										*/
										
										//NEW SMS Format
										$smsMsg = 'Dear client Your Vehicle '.$devName.' battery is low. Kindly check your vehicle. by '.$fetReseller[ci_weburl];
										
										if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "LowBattery"))
										{
											$data['tlai_dai_id'] = $record[tdai_id];
											$data['tlai_status'] = 1;
											$data['tlai_power'] = $lowbatsval;
											$data['tlai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
											//print_r($data);
											//exit;
											if($db->query_insert("tb_lowbattery_alert_info", $data))
												$res = 1;
											else $res = 0;
											echo "SMS 1";
										}
									}
								}
							}
						}
						elseif($record[tdai_alertBy] == "FuelTheft")	//// if Overstay alert
						{
							$data1=explode("#",$mydata);

							$fuel_sql ="select * from tb_deviceinfo,tb_fuel where imei = di_imeiId AND di_imeiId = '".$gpsdata[0]."' order by voltage ASC";
							$fuel_rows = $db->query($fuel_sql);
							$k=0;
							while($fuel_result = @mysql_fetch_assoc($fuel_rows))
							{
								$fuel_params[$fuel_result[tanksize]] = $fuel_result[voltage];
								$fuel_port = $fuel_result[di_Fuelport];
								$k++;
							}
							
							$strLevel = "";
							$endLevel = "";
							$strStayTime = "";
							$endStayTime = "";
							for($j1=count($data1); $j1 > 0; $j1--)		
							{
								$data2=explode("@",$data1[$j1]);
								if(count($data2)>1)
								{
									$data3=explode(",",$data2[1]);	
									$mph = round($data3[3]);
									$devDateTime = $data3[8]." ".$data3[9];
									$pos1=calLat($data3[2]);
									$pos2=calLong($data3[1]);
			
									  $d = preg_split("/[\s,]+/",$data3[7]);				
									 
									  foreach($d as $e){					
										  if(substr($e,0,3)=='[9='){
											$curFuelLevel  = str_replace(array('[9=',']'),'',$e); 
											break;
										  }					  
									  }				
							
									if(strlen($curFuelLevel)>3 && $strLevel =='' && $endLevel == '')
									{
										$curFuelLevel = $curFuelLevel/1000;
										$strLevel = getClosestElement($fuel_params,$curFuelLevel);	
										$strStayTime = $strLevel."#".$data3[9];
																				
									}
									else if(strlen($curFuelLevel)>3 && $strLevel !='' && $endLevel == '')
									{	
										$curFuelLevel = $curFuelLevel/1000;
										$endLevel = getClosestElement($fuel_params,$curFuelLevel);		
										$endStayTime = $endLevel."#".$data3[9];										
										$diff = $endLevel - $strLevel;	
																
										//echo 'sss'.$data3[9]." ".$strStayTime.' '.$diff." = ".$endLevel." - ".$strLevel."<br>";											
										//exit;
										if($diff > 1)
										{
											//echo 'sss'.$data3[9]." ".$strStayTime.' '.$record[tdai_alertSrc];
											$getAlertImeiInfo = "SELECT * FROM tb_fueltheft_info WHERE tfti_dai_id = ".$record[tdai_id]." and tfti_createDate like '".date("Y-m-d")."%' ORDER BY tfti_id DESC LIMIT 0,1";
											$resAlertImeiInfo = $db->query($getAlertImeiInfo);
											if($db->affected_rows == 0)
											{
												$mailMsg ='Your vehicle ' . strip_tags($devName) . ' fuel level has dropped aproximatey '.$diff.' ltrs. So kindly please check the vehicle.';
												$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
												
												//OLD SMS Format
												/*
												$smsMsg = "Dear Client, Your Vehicle ".$devName;
												$smsMsg .= " fuel level has dropped aproximatey ".$diff." ltrs. So kindly please check the vehicle.";
												$smsMsg .= " by ".$fetReseller[ci_weburl];
												*/
												
												//New SMS Format
						$smsMsg = 'Dear Client Your '.$devName.' fuel level dropped approx. by '.$diff.' ltrs. Kindly check your vehicle. by '.$fetReseller[ci_weburl];
												
												
												if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "FuelTheft"))
												{
													$data['tfti_dai_id'] = $record[tdai_id];
													$data['tfti_startLevelTime'] = $endStayTime;
													$data['tfti_endLevelTime'] = $strStayTime;
													//print_r($data);
													//exit;
													if($db->query_insert("tb_fueltheft_info", $data))
														echo "Done";
													else echo "no";													
												}
											}
											break;
										}
										
									}	
												
								}
							}			
						}
						elseif($record[tdai_alertBy] == "Immbolize")	// if Overspeed alert
						{
							$data1=explode("#",$mydata);
							$data2=explode("@",$data1[count($data1)-2]);		
							if(count($data2)>1)
							{
								$data3=explode(",",$data2[1]);			
								$devDateTime = $data3[8]." ".$data3[9];
								$spdLtd = explode("#",$record[tdai_alertSrc]);
								$spdLtd[0] = $spdLtd[1] -10;
							}	
							$getAlertImeiInfo = "SELECT * FROM tb_overspeed_alert_info WHERE toai_dai_id = ".$record[tdai_id]." and toai_createDate like '".date("Y-m-d")."%' ORDER BY toai_id DESC LIMIT 0,1";
							$resAlertImeiInfo = $db->query($getAlertImeiInfo);
							if($db->affected_rows == 0)		// first time vehicle reached max speed
							{								
								if($data3[3] >= $spdLtd[1])
								{
									$to = $record[di_mobileNo];
									$msg = "opa opa setdigout 1000";
										
									if(smsImmobilize($record, $fetReseller, $to, $msg))
									{										
										$mailMsg ='Your vehicle ' . strip_tags($devName) . ' over speed alarm  has been triggered. So kindly please check the vehicle.';
										$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
										
										$smsMsg = "Dear Client, Your Vehicle ".$devName;
										$smsMsg .= " over speed alarm  has been triggered. So kindly please check the vehicle.";
										$smsMsg .= " by ".$fetReseller[ci_weburl];
										
										if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "OverSpeed"))
										{
											$data['toai_dai_id'] = $record[tdai_id];
											$data['toai_maxSpeed'] = $spdLtd[1];
											$data['toai_devMaxSpeed'] = $data3[3];
											$data['toai_status'] = 0;
											$data['toai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
											//print_r($data);
											//exit;
											if($db->query_insert("tb_overspeed_alert_info", $data))
												echo "done";
											else echo "no";
										}
									}
								}
							}
							else
							{
								$fetAlertImeiInfo = $db->fetch_array($resAlertImeiInfo);
								//print_r($fetAlertImeiInfo);
								
								// when vehicle reached low speed no alert & when vehicle reached max speed send alert
								if($fetAlertImeiInfo[toai_minSpeed] == 0 && $fetAlertImeiInfo[toai_maxSpeed] != 0 && $data3[3] <= $spdLtd[0])	
								{
									$to = $record[di_mobileNo];
									$msg = "opa opa setdigout 0000";
									if(smsImmobilize($record, $fetReseller, $to, $msg))
									{										
										$data['toai_minSpeed'] = $spdLtd[0];
										$data['toai_devMinSpeed'] = $data3[3];
										$data['toai_status'] = 1;
										$data['toai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_update("tb_overspeed_alert_info", $data , "toai_id=".$fetAlertImeiInfo[toai_id]))
											$res = 1;
										else $res = 0;
									}
								}
								else if($fetAlertImeiInfo[toai_minSpeed] != 0 && $fetAlertImeiInfo[toai_maxSpeed] != 0 && $data3[3] >= $spdLtd[1])
								{
									$to = $record[di_mobileNo];
									$msg = "opa opa setdigout 1000";
										
									if(smsImmobilize($record, $fetReseller, $to, $msg))
									{
										$data['toai_dai_id'] = $record[tdai_id];
										$data['toai_maxSpeed'] = $spdLtd[1];
										$data['toai_devMaxSpeed'] = $data3[3];
										$data['toai_status'] = 0;
										$data['toai_deliveryTime'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_insert("tb_overspeed_alert_info", $data))
											echo "done";
										else echo "no";
									}	
								}
							}
						}
						elseif(strpos($record[tdai_alertBy],"INALERT_") >= 0)
						{
							$data1=explode("#",$mydata);
							$data2=explode("@",$data1[count($data1)-2]);
							$portNo = explode("_",$record[tdai_alertBy]);
							
							if(count($data2)>1)
							{
								$data3=explode(",",$data2[1]);	
								$devDateTime = $data3[8]." ".$data3[9];		
								//echo $data3[7]." ".$portNo[1]."<br>";
								$d = preg_split("/[\s,]+/",$data3[7]);	
							    $igval = splitParam($portNo[1],$data3[7]);
							}
							$getIgnitAlertImeiInfo = "SELECT * FROM tb_igntion_alert_info WHERE tiai_dai_id = ".$record[tdai_id]." and tiai_createDate like '".date("Y-m-d")."%' ORDER BY tiai_id DESC LIMIT 0,1";
							$resIgnitAlertImeiInfo = $db->query($getIgnitAlertImeiInfo);
							if($db->affected_rows == 0)		// first time vehicle reached max speed
							{								
								if($igval == 1)
								{
									$mailMsg ='Your vehicle ' . strip_tags($devName) . '\'s '.$portNo[0].' is ON now.';
									$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
									
									//OLD SMS Format
									/*
									$smsMsg = "Dear Client, Your Vehicle ".$devName;
									$smsMsg .= "\'s ".$portNo[0]." is ON now.";
									$smsMsg .= " by ".$fetReseller[ci_weburl];
									*/
									
									//New SMS Format
									$smsMsg = 'Your Vehicle '.$devName.' '.$portNo[0].' is ON at '.$vehiLoca.'. by '.$fetReseller[ci_weburl];
									
										
									if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "Custom - ".$portNo[0]))
									{
										$data['tiai_dai_id'] = $record[tdai_id];
										$data['tiai_status'] = $igval;
										$data['tiai_delveryTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_insert("tb_igntion_alert_info", $data))
											echo "done";
										else echo "no";
									}
								}
							}
							else
							{
								$fetIgnitAlertImeiInfo = $db->fetch_array($resIgnitAlertImeiInfo);
								//print_r($fetIgnitAlertImeiInfo);
								
								// when vehicle reached low speed no alert & when vehicle reached max speed send alert
								if($fetIgnitAlertImeiInfo[tiai_status] == 1 && $igval == 0)	
								{
									$mailMsg ='Your vehicle ' . strip_tags($devName) . '\'s '.$portNo[0].' is OFF now.';
									$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
									
									//OLD SMS Format
									/*
									$smsMsg = "Dear Client, Your Vehicle ".$devName;
									$smsMsg .= "\'s ".$portNo[0]." is OFF now.";
									$smsMsg .= " by ".$fetReseller[ci_weburl];
									*/
									
									//NEW SMS Format
									$smsMsg = 'Your Vehicle '.$devName.' '.$portNo[0].' is OFF at '.$vehiLoca.'. by '.$fetReseller[ci_weburl];
									
										
									if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "Ignition"))
									{
										$data['tiai_dai_id'] = $record[tdai_id];
										$data['tiai_status'] = $igval;
										$data['tiai_delveryTime2'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_update("tb_igntion_alert_info", $data , "tiai_id=".$fetIgnitAlertImeiInfo[tiai_id]))
											$res = 1;
										else $res = 0;
									}
								}
								else if($fetIgnitAlertImeiInfo[tiai_status] == 0 && $igval == 1)	
								{
									$mailMsg ='Your vehicle ' . strip_tags($devName) . 's '.$portNo[0].' is ON now.';
									$mailMsg .= '<br><br><strong>Description is :</strong> ' . strip_tags(ucfirst($record[tdai_description]));
									
									//OLD SMS Format
									/*
									$smsMsg = "Dear Client, Your Vehicle ".$devName;
									$smsMsg .= "\'s ".$portNo[0]." is ON now.";
									$smsMsg .= " by ".$fetReseller[ci_weburl];
									*/
									
									// NEW SMS Format
									$smsMsg = 'Your Vehicle '.$devName.' '.$portNo[0].' is ON at '.$vehiLoca.'. by '.$fetReseller[ci_weburl];
									
										
									if(sendOtherAlert($record, $fetReseller, $mailMsg, $smsMsg, "Ignition"))
									{
										$data['tiai_dai_id'] = $record[tdai_id];
										$data['tiai_status'] = $igval;
										$data['tiai_delveryTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
										//print_r($data);
										//exit;
										if($db->query_insert("tb_igntion_alert_info", $data))
											echo "done";
										else echo "no";
									}	
								}
							}
						}
					}
					
				}
				
			}
		}
	}
}
function splitParam($portNo,$str)
{
	$ind3 = explode(" ",$str);
	for($h=0;$h<count($ind3);$h++)
	{
		$findPort = "[".$portNo."=";
		if(strpos($ind3[$h],$findPort) > -1)
		{
			$ind4 =str_replace("]","", $ind3[$h]);
			$ind4 = str_replace($findPort,"",$ind4);
			return $ind4;
			break;
		}
	}
}
function smsImmobilize($fetData,$fetReseller,$to, $msg)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	$from = "";
	//echo $from." ".$to." ".$msg;
	$smsres= sendGatewaySMS($from,$to,$msg,$fetReseller[ci_smsGatewayUri],$fetReseller[ci_smsGatewayUsername],$fetReseller[ci_smsGatewayPassword],$fetReseller[ci_smsGatewaySenderId]);
	//return 1;
	//$smsres = 0;
	if($smsres)
	{
		$smsdata['tsi_mobileno'] = $to;
		$smsdata['tsi_tgai_id'] = $fetData[tdai_id];
		$smsdata['tsi_smsResult'] = $smsres;
		$smsdata['tsi_message'] = urlencode($msg);
		$smsdata['tsi_smsType'] = "BUZZER";		
		//print_r($smsdata);		
		//exit;
		if($db->query_insert("tb_smsinfo", $smsdata))
		/*	return 1;
		else return 0;
	
		$cdata["tii_clientId"] = $_GET[cltId];
		$cdata["tii_devId"] = $_GET[devId];
		$cdata["tii_status"] = 1;
		$cdata["tii_mobileNo"] = $to;
		$cdata["tii_stopMsg"] = $msg;
		$cdata["tii_smsStatus"] = $smsres;
		//print_r($cdata);
		//exit;*/
		if($db->query_insert("tb_immbolize_info", $cdata))
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	
}
// Condition check for geofence both 
function smsBothAlertFunc($gid,$aid,$src,$nooftime,$inout,$devDateTime,$devImei,$inorout)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	//print_r($_GET);
	//echo $aid."  ".$nooftime." cs ". $inorout." ds ".$inout." ".$devDateTime."<br><br>";
	//echo "<br><br>";
	//exit;
	$getAlertImeiInfo = "SELECT * FROM tb_geoalertinfo WHERE tgai_geoAssignId = ".$aid." and tgai_assignDevId = '".$devImei."' AND tgai_createDate like '".date("Y-m-d",strtotime($devDateTime))."%' ORDER BY tgai_id";
	$resAlertImeiInfo = $db->query($getAlertImeiInfo);
	
	if($db->affected_rows == 0 && $inorout == "in")
	{
			$smsStatus = sendGeofenceAlert($aid,$devDateTime,$inorout);
			//echo "<br>";
			if($smsStatus)
			{
				$data['tgai_assignDevId'] = $devImei;
				$data['tgai_geoAssignId'] = $aid;
				$data['tgai_inoutStatus'] = 0;
				$data['tgai_alertCount'] = 1;
				$data['tgai_alertType'] = $inorout;
				$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
				//print_r($data);
				//exit;
				if($db->query_insert("tb_geoalertinfo", $data))
					$res = 1;
				else $res = 0;
				echo "SMS";
			}

	}
	elseif($db->affected_rows == 1 && $inorout == "out")												
	{
		$fetAlertImeiInfo = $db->fetch_array($resAlertImeiInfo);		
		if($fetAlertImeiInfo[tgai_inoutStatus] == 0 && $inorout == "out")
		{
			$smsStatus = sendGeofenceAlert($aid,$devDateTime,$inorout);
			if($smsStatus)
			{
				$data['tgai_assignDevId'] = $devImei;
				$data['tgai_geoAssignId'] = $aid;
				$data['tgai_inoutStatus'] = 1;
				$data['tgai_alertCount'] =  $fetAlertImeiInfo[tgai_alertCount] + 1;
				$data['tgai_alertType'] = $inorout;
				$data['tgai_reachdevTime2'] = date("Y-m-d H:i:s",strtotime($devDateTime));
				//print_r($data);
				//exit;
				if($db->query_update("tb_geoalertinfo", $data , "tgai_id=".$fetAlertImeiInfo[tgai_id]))
				{
					$sql = "DELETE FROM tb_geoalertinfo WHERE tgai_id=".$fetAlertImeiInfo[tgai_id];
					$db->query($sql);
					$res = 1;
				}
				else $res = 0;
				echo "SMS";
			}
		}
	}
}

// Condition check for geofence entered or left
function smsmAlertFunc($gid,$aid,$src,$nooftime,$inout,$devDateTime,$devImei,$inorout)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	//print_r($_GET);
	//echo $aid."  ".$nooftime." cs ". $inorout." ds ".$inout." ".$devDateTime."<br><br>";
	//echo "<br><br>";
	
	$getAlertImeiInfo = "SELECT * FROM tb_geoalertinfo WHERE tgai_assignDevId = '".$devImei."' AND tgai_createDate like '".date("Y-m-d",strtotime($devDateTime))."%' ORDER BY tgai_id DESC LIMIT 0,1";
	$resAlertImeiInfo = $db->query($getAlertImeiInfo);
	if($db->affected_rows == 0)
	{
		if($inout == 'in' && $inorout == $inout)
		{
			$smsStatus = sendGeofenceAlert($aid,$devDateTime,$inorout);
			//echo "<br>";
			if($smsStatus)
			{
				$data['tgai_assignDevId'] = $devImei;
				$data['tgai_geoAssignId'] = $aid;
				$data['tgai_inoutStatus'] = 0;
				$data['tgai_alertCount'] = 1;
				$data['tgai_alertType'] = $inout;
				$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
				//print_r($data);
				//exit;
				if($db->query_insert("tb_geoalertinfo", $data))
					$res = 1;
				else $res = 0;
				echo "SMS";
			}
		}
		elseif($inout == 'out' && $inorout != $inout)
		{
				$data['tgai_assignDevId'] = $devImei;
				$data['tgai_geoAssignId'] = $aid;
				$data['tgai_inoutStatus'] = 0;
				$data['tgai_alertCount'] = 1;
				$data['tgai_alertType'] = $inout;
				$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
				//print_r($data);
				//exit;
				if($db->query_insert("tb_geoalertinfo", $data))
					$res = 1;
				else $res = 0;
		}

	}
	else													//if($nooftime == 0 || ($fetAlertImeiInfo[tgai_alertCount] < $nooftime))
	{
		$fetAlertImeiInfo = $db->fetch_array($resAlertImeiInfo);
		
		$getAlertInfo = "SELECT count(*) as pastTotal FROM tb_geoalertinfo WHERE tgai_geoAssignId = ".$aid." AND tgai_inoutStatus = 1 AND tgai_createDate like '".date("Y-m-d",strtotime($devDateTime))."%'";
		$resAlertInfo = $db->query($getAlertInfo);
		$fetAlertInfo = $db->fetch_array($resAlertInfo);
		
		
		//echo "<br>".$fetAlertImeiInfo[tgai_geoAssignId]." ".$aid." ".$fetAlertImeiInfo[tgai_inoutStatus]." ".$nooftime." ".$fetAlertImeiInfo[tgai_alertCount]." ". $inorout." ".$inout."<br>";
		//print_r($fetAlertInfo);
		/*echo "<pre>";
		print_r($fetAlertImeiInfo);
		//
		echo "</pre>";*/
		//echo $fetAlertImeiInfo[tgai_id];
		//echo "<br> 1 ".$fetAlertInfo[pastTotal]." ".$fetAlertImeiInfo[tgai_alertCount]."<".$nooftime."<br>";
		if($fetAlertImeiInfo[tgai_geoAssignId] == $aid && $fetAlertInfo[pastTotal] < $nooftime)
		{
			//echo "<br>".$fetAlertInfo[pastTotal]." ".$fetAlertImeiInfo[tgai_alertCount]."<".$nooftime."<br>";
			if($fetAlertImeiInfo[tgai_inoutStatus] == 0)
			{
				//echo $fetAlertImeiInfo[tgai_alertCount]."<".$nooftime."<br>";
				if($inout == 'in' && $inorout != $inout)
				{
					$data['tgai_inoutStatus'] = 1;
					$data['tgai_reachdevTime2'] = date("Y-m-d H:i:s",strtotime($devDateTime));
					//print_r($data);
					//exit;
					if($db->query_update("tb_geoalertinfo", $data , "tgai_id=".$fetAlertImeiInfo[tgai_id]))
						$res = 1;
					else $res = 0;
					
				}
				elseif($inout == 'out' && $inorout == $inout)
				{
					$smsStatus = sendGeofenceAlert($aid,$devDateTime,$inorout);
					if($smsStatus)
					{
						$data['tgai_inoutStatus'] = 1;
						$data['tgai_reachdevTime2'] = date("Y-m-d H:i:s",strtotime($devDateTime));
						//print_r($data);
						//exit;
						if($db->query_update("tb_geoalertinfo", $data , "tgai_id=".$fetAlertImeiInfo[tgai_id]))
							$res = 1;
						else $res = 0;
						
						echo "SMS";
					}
				}
			}
			else
			{
				//echo $fetAlertImeiInfo[tgai_alertCount]."<".$nooftime."<br>";
				//echo "<br>".$inout." ".$inorout;
				if($inout == 'in' && $inorout == $inout)
				{
					$smsStatus = sendGeofenceAlert($aid,$devDateTime,$inorout);
					if($smsStatus)
					{
						$data['tgai_assignDevId'] = $devImei;
						$data['tgai_geoAssignId'] = $aid;
						$data['tgai_inoutStatus'] = 0;
						$data['tgai_alertCount'] =  $fetAlertInfo[tgai_alertCount] + 1;
						$data['tgai_alertType'] = $inout;
						$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
						//print_r($data);
						//exit;
						if($db->query_insert("tb_geoalertinfo", $data))
							$res = 1;
						else $res = 0;
						echo "SMS";
					}
				}
				elseif($inout == 'out' && $inorout != $inout)
				{
						$data['tgai_assignDevId'] = $devImei;
						$data['tgai_geoAssignId'] = $aid;
						$data['tgai_inoutStatus'] = 0;
						$data['tgai_alertCount'] =  $fetAlertInfo[tgai_alertCount] + 1;
						$data['tgai_alertType'] = $inout;
						$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
						//print_r($data);
						//exit;
						
						if($db->query_insert("tb_geoalertinfo", $data))
							$res = 1;
						else $res = 0;
				}
			}
		}
		elseif($fetAlertImeiInfo[tgai_geoAssignId] != $aid && $fetAlertImeiInfo[tgai_inoutStatus] == 1 && $fetAlertInfo[tgai_alertCount] < $nooftime)
		{
			//print_r($fetAlertImeiInfo);
			if($inout == 'in' && $inorout == $inout)
			{
				$smsStatus = sendGeofenceAlert($aid,$devDateTime,$inorout);
				if($smsStatus)
				{
					$data['tgai_assignDevId'] = $devImei;
					$data['tgai_geoAssignId'] = $aid;
					$data['tgai_inoutStatus'] = 0;
					$data['tgai_alertCount'] =  $fetAlertInfo[tgai_alertCount] + 1;
					$data['tgai_alertType'] = $inout;
					$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
					//print_r($data);
					//exit;
					
					if($db->query_insert("tb_geoalertinfo", $data))
						$res = 1;
					else $res = 0;
					echo "SMS";
				}
			}
			elseif($inout == 'out' && $inorout != $inout)
			{
					$data['tgai_assignDevId'] = $devImei;
					$data['tgai_geoAssignId'] = $aid;
					$data['tgai_inoutStatus'] = 0;
					$data['tgai_alertCount'] =  $fetAlertInfo[tgai_alertCount] + 1;
					$data['tgai_alertType'] = $inout;
					$data['tgai_reachdevTime1'] = date("Y-m-d H:i:s",strtotime($devDateTime));
					//print_r($data);
					//exit;
					
					if($db->query_insert("tb_geoalertinfo", $data))
						$res = 1;
					else $res = 0;
			}
		}
	}

}

// Shoot alert for geofence
function sendGeofenceAlert($geoAssId,$devDateTime,$inoutStatus)
{
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

	$getData = "SELECT * FROM tb_assigngeofence,tb_deviceinfo,tb_geofence_info,tb_clientinfo WHERE ci_id = tag_clientId AND tgi_id = tag_geofenceId AND di_id = tag_diId AND tag_id = ".$geoAssId;
	$resData = mysql_query($getData);
	if(@mysql_affected_rows() > 0)
	{
		$fetData = mysql_fetch_assoc($resData);
		//print_r($fetData);
	
		$getReseller = "select * from tb_clientinfo where ci_id = ".$fetData[ci_clientId];
		$resReseller = mysql_query($getReseller);
		$fetReseller = @mysql_fetch_assoc($resReseller);
		
		if($fetData[di_deviceName])
			$devName = $fetData[di_deviceName];
		else
			$devName = $fetData[di_deviceId];
			
		if($fetData[tag_inout] == "in")

			$status = "entered zone";
		else if($fetData[tag_inout] == "out")
			$status = "left zone";		
		else if($fetData[tag_inout] == "both")
		{
			if($inoutStatus == "in")
				$status = "entered zone";
			else if($inoutStatus == "out")
				$status = "left zone";

		}
		$mailMsg ='Your Vehicle ' . strip_tags($devName) ." has ".$status." ".ucfirst($fetData[tgi_name])." around ".date("d M Y H:i:s A",strtotime($devDateTime));
		
		//OLD SMS Format
		/*
		$smsMsg = "Geofence Alert: ".$devName;
		$smsMsg .= " has ".$status." ".$fetData[tgi_name]." at ".date("H:i:s A",strtotime($devDateTime));
		$smsMsg .= " by ".$fetReseller[ci_weburl];
		*/
		
		//NEW SMS Format
		$smsMsg = 'Geofence Alert: '.$devName.' has '.$status.' '.$fetData[tgi_name]' at '.date("H:i:s A",strtotime($devDateTime)).' by '.$fetReseller[ci_weburl];
		
		
		if($fetData[tag_alertType] == "" && $fetData[tag_alertSrc] == "")	
		{
			$contactIdArr = explode(",",$fetData[tag_contactIds]);
			for($k =0; $k < count($contactIdArr)-1; $k++)
			{
				$sql2 = "SELECT * FROM tb_client_contact_info WHERE tcci_id = '".$contactIdArr[$k]."' AND tcci_clientId =".$fetData[tag_clientId];
				$res2 = $db->query($sql2);
				$fet2 = $db->fetch_array($res2);
				if($fet2[tcci_srcType] == "Email")
				{
					geoAlertMail($fetData,$fetReseller,$fet2[tcci_source],$inoutStatus,$devDateTime,$mailMsg,"Geofence");
				}
				else if($fet2[tcci_srcType] == "Mobile")
				{
					geoAertSMS($fetData,$fetReseller,$fet2[tcci_source],$inoutStatus,$devDateTime,$smsMsg,"Geofence");
				}
			}
		}
		else
		{
			$contactIdArr = explode(",",$fetData[tag_alertSrc]);
			for($k =0; $k < count($contactIdArr)-1; $k++)
			{
				if($fetData[tag_alertType] == "Email")		
				{
					geoAlertMail($fetData,$fetReseller,$contactIdArr[$k],$inoutStatus,$devDateTime,$mailMsg,"Geofence");
				}
				else if($fetData[tag_alertType] == "Mobile")		
				{
					geoAertSMS($fetData,$fetReseller,$contactIdArr[$k],$inoutStatus,$devDateTime,$smsMsg,"Geofence");
				}
			}
			
		}
		//exit;
		
		return 1;
	}
}


// Shoot alert for date
function sendOtherAlert($fetData,$fetReseller, $mailMsg, $smsMsg,$alertType)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	
	
	if($fetData[tdai_alertType] == "" && $fetData[tdai_source] == "")		
	{
		$contactIdArr = explode(",",$fetData[tdai_contactIds]);
		for($k =0; $k < count($contactIdArr)-1; $k++)
		{
			$sql2 = "SELECT * FROM tb_client_contact_info WHERE tcci_id = '".$contactIdArr[$k]."' AND tcci_clientId =".$fetData[tdai_clientId];
			$res2 = $db->query($sql2);
			$fet2 = $db->fetch_array($res2);
			if($fet2[tcci_srcType] == "Email")
			{
				geoAlertMail($fetData,$fetReseller,$fet2[tcci_source],$inoutStatus,$devDateTime,$mailMsg,$alertType);
			}
			else if($fet2[tcci_srcType] == "Mobile")
			{
				geoAertSMS($fetData,$fetReseller,$fet2[tcci_source],$inoutStatus,$devDateTime,$smsMsg,$alertType);
			}
		}
	}
	else
	{
		$contactIdArr = explode(",",$fetData[tdai_source]);
		for($k =0; $k < count($contactIdArr)-1; $k++)
		{
			if($fetData[tdai_alertType] == "Email")		
			{
				$mailMsg ='Your Vehicle ' . strip_tags($devName) ." has ".$status." ".ucfirst($fetData[tgi_name])." around ".date("d M Y H:i:s A",strtotime($devDateTime));
				geoAlertMail($fetData,$fetReseller,$contactIdArr[$k],$inoutStatus,$devDateTime,$mailMsg,$alertType);
			}
			else if($fetData[tdai_alertType] == "Mobile")		
			{
				geoAertSMS($fetData,$fetReseller,$contactIdArr[$k],$inoutStatus,$devDateTime,$smsMsg,$alertType);
			}
		}
		
	}
	//exit;
	return 1;
}


//Trigger SMS alert
function geoAertSMS($fetGeoData,$fetGeoReseller,$sourceGeo,$inoutStatus,$devDateTime,$msg,$alertType)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	
	if($fetGeoData[di_deviceName])
		$devName = $fetGeoData[di_deviceName];
	else
		$devName = $fetGeoData[di_deviceId];
		
	if($fetGeoData[tag_inout] == "in")
		$status = "entered zone";
	else if($fetGeoData[tag_inout] == "out")
		$status = "left zone";
	else if($fetGeoData[tag_inout] == "both")
	{
		if($inoutStatus == "in")
			$status = "entered zone";
		else if($inoutStatus == "out")
			$status = "left zone";
	}

	$info = $devName." has ".$status." ".$fetGeoData[tgi_name]." at ".date("d M Y H:i:s",strtotime($devDateTime))." ".$fetGeoData[tag_alertType]." ".$fetGeoData[tag_alertSrc]." ".$fetGeoData[tag_contactIds];

	$from = "";
	$to = $sourceGeo;
	echo $msg;
	//exit;
	
	
	$smsres= sendGatewaySMS($from,$to,$msg,$fetGeoReseller[ci_smsGatewayUri],$fetGeoReseller[ci_smsGatewayUsername],$fetGeoReseller[ci_smsGatewayPassword],$fetGeoReseller[ci_smsGatewaySenderId]);
		

	//$smsString = $fetGeoData[tag_alertSrc].",".$fetGeoReseller[ci_smsGatewayUri].",".$fetGeoReseller[ci_smsGatewayUsername].",".$fetGeoReseller[ci_smsGatewayPassword].",".$fetGeoReseller[ci_smsGatewaySenderId].",".$smsres;
//writeGeoData(date("d-m-Y",strtotime($devDateTime)),date("H:i:s",strtotime($devDateTime)),strip_tags($info),$smsString);	

	/*$smsdata['tsi_deviceId'] = $fetGeoData[di_id];
	$smsdata['tsi_mobileno'] = $to;
	$smsdata['tsi_tgai_id'] = $fetGeoData[tag_id];
	$smsdata['tsi_smsResult'] = $smsres;
	$smsdata['tsi_message'] = urlencode($msg);
	$smsdata['tsi_smsType'] = $alertType;		
	//print_r($smsdata);		
	//exit;
	if($db->query_insert("tb_smsinfo", $smsdata))
		return 1;
	else return 0;*/
	

}

//Trigger Email alert
function geoAlertMail($fetGeoData,$fetGeoReseller,$to,$inoutStatus,$devDateTime,$mailMsg,$alertType)
{
	$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
	$db->connect(); 
	
	if($fetGeoData[di_deviceName])
		$devName = $fetGeoData[di_deviceName];
	else
		$devName = $fetGeoData[di_deviceId];
		
	if($fetGeoData[tag_inout] == "in")
		$status = "entered zone";
	else if($fetGeoData[tag_inout] == "out")
		$status = "left zone";		
	else if($fetGeoData[tag_inout] == "both")
	{
		if($inoutStatus == "in")
			$status = "entered zone";
		else if($inoutStatus == "out")
			$status = "left zone";
	}

	$info = $devName." has ".$status." ".$fetGeoData[tgi_name]." at ".date("d M Y H:i:s",strtotime($devDateTime))." ".$fetGeoData[tag_alertType]." ".$fetGeoData[tag_alertSrc]." ".$fetGeoData[tag_contactIds];

	$sub = $alertType." Alert Mail from ".$fetGeoReseller[ci_clientName];
	$fr = $fetGeoReseller[ci_clientName];				
	
	$message ='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
	$message .='<html>';
	$message .='<head>';
	$message .='<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">';
	$message .='<title>'.$alertType.' Alert Mail from '.$fetGeoReseller[ci_clientName].'</title>';
	$message .='</head>';
	$message .='<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">';
	$message .='<table width="100%" border="0" cellspacing="0" cellpadding="15">';
	$message .='<tr>';
	$message .='<td align="center" valign="middle" bgcolor="#ced9a7">';
	$message .='<table width="600" border="0" cellpadding="0" cellspacing="2" bgcolor="#2b302d">';
	$message .='<tr>';
	$message .='<td align="left" valign="top" bgcolor="#FFFFFF">';
	$message .='<table width="100%" border="0" cellspacing="0" cellpadding="0">';
	$message .='<tr>';
	$message .='<td height="110" align="left" valign="middle" background="http://trackonwheels.com/gpsapp/images/header.gif" bgcolor="#164d65" style="padding-left:10px; padding-right:10px; font-family: Georgia, Times New Roman, Times, serif; color:#FFFFFF;">';
	$message .='<div align="right" style="font-size:12px;">'.date("d M Y").'</div>';
	$message .='<div style="font-size:40px;">'.$alertType.' Alert</div>';
	$message .='<div style="font-size:18px;"> </div>';
	$message .='</td>';
	$message .='</tr>';
	
	$message .='<tr>';
	$message .='<td align="left" valign="top">';
	$message .='<table width="596" border="0" cellspacing="0" cellpadding="0">';
	$message .='<tr>';
	
	$message .='<td width="100%" align="left" valign="top" style="padding:15px; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; color:#333333; line-height:130%;">';
	$message .='<span style="font-size:18px;font-weight:bold;color:#006699;font-family:Verdana, Arial, Helvetica, sans-serif;line-height:150%;">Greetings From - '.$fetGeoReseller[ci_clientName].'</span><br>';
	$message .='<br>';
	$message .='Dear '.ucfirst($fetGeoData[ci_clientName]).'!,<br>';
	$message .='<br>'.$mailMsg.'<br><br>';
	$message .='<br>Please Login to on website: <br><br>';
	
	$message .='<a href="http://'.$fetGeoReseller[ci_weburl].'" target="_blank" style="font-size:16px; color:#579b12;"><b>'.$fetGeoReseller[ci_weburl].'</b></a><br>';
	$message .='<br>';
	$message .='</td>';
	$message .='</tr>';
	$message .='</table>';
	$message .='</td>';
	$message .='</tr>';
	$message .='<tr>';
	$message .='<td align="left" valign="top" bgcolor="#2b302d">';
	$message .='<table width="100%" border="0" cellspacing="0" cellpadding="10">';
	$message .='<tr>';
	$message .='<td align="left" valign="top" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; color:#FFFFFF;"><b>'.$fetGeoReseller[ci_clientName].'</b><br>';
	$message .= 'Address: '.$fetGeoReseller[ci_address].'<br>';
	$message .= 'Email: <a href="mailto:'.$fetGeoReseller[ci_email1].'" style="color:#569b11;">'.$fetGeoReseller[ci_email1].'</a><br>';
	$message .= 'Website: <font style="color:#569b11;">'.$fetGeoReseller[ci_website].'</font><br>';
	$message .= 'Phone: '.$fetGeoReseller[ci_phoneNumber].'<br></td>';
	$message .= '<td align="right"><img src="'.CLIENTLOGOPATH.$fetGeoReseller[ci_clientLogo].'" alt="Logo" /></td>';
	$message .='</tr>';
	$message .='</table>';
	$message .='</td>';
	$message .='</tr>';
	$message .='</table>';
	$message .='</td>';
	$message .='</tr>';
	$message .='</table>';
	$message .='</td>';
	$message .='</tr>';
	$message .='</table>';
	$message .='</body>';
	$message .='</html>';
	
	echo $message;
	//exit;	
	
	
	/*$mailres = sendSMTPMail($to,$sub,$message,$fetGeoReseller[ci_clientName],$fetGeoReseller[ci_smtpHostname],$fetGeoReseller[ci_smtpUsername],$fetGeoReseller[ci_smtpPassword],$fetGeoReseller[ci_smtpUsername]);
	
	//$mailString = $to.",".$fetGeoReseller[ci_clientName].",".$fetGeoReseller[ci_smtpHostname].",".$fetGeoReseller[ci_smtpUsername].",".$fetGeoReseller[ci_smtpPassword].",".$fetGeoReseller[ci_smtpUsername].",".$mailres;
	//writeGeoData(date("d-m-Y",strtotime($devDateTime)),date("H:i:s",strtotime($devDateTime)),strip_tags($info),$mailString);
	
	$maildata['tmi_deviceId'] = $fetGeoData[di_id];
	$maildata['tmi_email'] = $to;
	$maildata['tmi_tgai_id'] = $fetGeoData[tag_id];
	$maildata['tmi_mailResult'] = $mailres;
	$maildata['tmi_message'] = urlencode($message);
	$maildata['tmi_mailType'] = $alertType;		
	//print_r($maildata);		
	//exit;
	if($db->query_insert("tb_mail_info", $maildata))
		return 1;
	else return 0;*/
	
	
}


function writeGeoData($gdate,$gtime,$mesg,$mailString)
{
	$file_name = "gdata/".$gdate.".txt";
	//open file for writng and place pointer at the end
	$handle = fopen($file_name, 'a+');

	if(!$handle)
	{
		die("couldn't open file <i>$file_name</i>");
	}
	
	fwrite($handle, $gtime." - ".$mesg." - ".$mailString."\n");
	return 1;

}
?>
